package com.dts.controller;

import com.dts.entity.Good;
import com.dts.service.GoodService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/good")
public class GoodController {

    @Autowired
    private GoodService goodService;

    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        List<Good> list = goodService.getList();
        request.setAttribute("goods", list);
        return "/list";
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam("id") int id,HttpServletRequest request) {
        goodService.delete(id);
        return "redirect:/good/list";
    }

    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String description = request.getParameter("description");
        Good good = new Good();
        good.setName(name);
        good.setPrice(Double.parseDouble(price));
        good.setDescription(description);
        goodService.add(good);
        return "redirect:/good/list";
    }

    @RequestMapping("/update")
    public String update(HttpServletRequest request) {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String description = request.getParameter("description");
        Good good = new Good();
        good.setId(Integer.parseInt(id));
        good.setName(name);
        good.setPrice(Double.parseDouble(price));
        good.setDescription(description);
        goodService.update(good);
        return"redirect:/good/list";
    }


}
